<?php

class UserModel extends CI_Model {
 
    public function __construct()
    {
        parent::__construct();
    }
	
	public function isLoginValid($username, $password)
	{
		$query = $this->db->get_where('users', array(
			'username' => $username,
			'password' => hash('sha256', $password)
		));
		return $query->num_rows != 0;
	}
	
	public function getUserID($username)
	{
		$this->db->select('user_id');
		$query = $this->db->get_where('users', array(
			'username' => $username
		));
		$result = $query->result();
		return $result[0]->user_id;
	}
	
	public function setLoggedIn($username)
	{
		$this->load->library('session');
		
		$user_id = $this->getUserID($username);
		
		$this->session->set_userdata('logged_in', true);
		$this->session->set_userdata('user_id', $user_id);
		$this->session->set_userdata('username', $username);
		
		$this->db->where('user_id', $user_id);
		$this->db->update('users', array('last_logged_in' => time()));
	}
	
	public function isLoggedIn()
	{
		$this->load->library('session');
		
		return $this->session->userdata('logged_in') == true;
	}
	
	public function setLoggedOut()
	{
		$this->load->library('session');
		
		$this->session->sess_destroy();
	}
	
	public function addUser($username, $password)
	{
		$this->db->insert('users', array(
			'username' => $username,
			'password' => hash('sha256', $password),
			'last_logged_in' => time()
		));
	}
}